<template>
    <div class="materials-file">
        <HeaderBackBtn @back-btn="onBackBtn" />
        <article class="main">
            <el-scrollbar wrap-class="material-file-scrollbar-wrapper" @scroll="handleScroll">
                <section class="file-item" :ref="fileItemRef" :data-id="file.docId" v-for="(file, index) in fileList"
                    :key="file.docId">
                    <div class="file-title">
                        <div class="title">{{ getFileTitle(file.docName) }}</div>
                        <div class="date">{{ file.createTime }}</div>
                    </div>
                    <div class="file-content">
                        <vue-office-docx v-if="file.docSuffix == 'docx'" :src="file.docUrl"
                            @rendered="rendered(file, index)" @error="errorHandler" />
                        <vue-office-excel v-else-if="file.docSuffix == 'xlsx'" :src="file.docUrl"
                            @rendered="rendered(file, index)" style="height: 100vh;" @error="errorHandler" />
                        <vue-office-pdf v-else-if="file.docSuffix == 'pdf'" :src="file.docUrl"
                            @rendered="rendered(file, index)" @error="errorHandler" />
                        <video class="video-controls" v-else-if="file.docSuffix == 'mp4'" controls>
                            <source :src="file.docUrl" type="video/mp4">
                        </video>
                    </div>
                    <el-empty v-if="isFileError" :image-size="200" description="资料加载失败" />
                </section>
                <el-empty v-if="fileList.length == 0" :image-size="200" description="暂无数据" />
            </el-scrollbar>
        </article>
    </div>
</template>

<script setup>
import { addLearningProgress } from '@/api/learn/materials.js'
import { debounce, throttled } from '@/utils/index.js'
import useUserStore from '@/store/modules/user'
import HeaderBackBtn from '@/components/HeaderBackBtn'
//引入VueOffice组件
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import VueOfficePdf from '@vue-office/pdf'

//引入相关样式
import '@vue-office/docx/lib/index.css'
//引入相关样式
import '@vue-office/excel/lib/index.css'

const router = useRouter()
function onBackBtn() {
    // router.push({ path: '/learn-center/materials' })
    router.go(-1)
}
const historyParams = history.state
const fileList = ref(historyParams.fileList || [])
const libId = historyParams.libId

let itemRefs = []
const fileItemRef = el => {
    if (el) {
        const dataId = el.getAttribute('data-id')
        let index = itemRefs.findIndex(ele => ele.getAttribute('data-id') == dataId)
        if (index != -1) {
            itemRefs[index] = el
        } else {
            itemRefs.push(el)
        }
    }
}

function rendered(file, index) {
    console.log('渲染完成', index, file);
}
const isFileError = ref(false)
function errorHandler(e) {
    console.log('error', e);
    isFileError.value = true
}

// 去除文件后缀名
function getFileTitle(fileName) {
    var filenameWithoutExtension = fileName.replace(/\.[^/.]+$/, "")
    return filenameWithoutExtension
}


const top = ref(627)


onBeforeUpdate(() => {
    itemRefs = []
})

function handleScroll({ scrollTop, scrollLeft }) {
    itemRefs.forEach((ele, index) => {
        if (scrollTop >= ele.offsetTop) {
            const docId = ele.getAttribute('data-id')
            debounceAdd(docId)
        }
    })
}

const debounceAdd = throttled(async (docId) => {
    await updateLearningProgress(docId)
}, 2000)

const userStore = useUserStore()
let userInfoRes = {}
userStore.getInfo().then(res => {
    userInfoRes = res.data?.user || {}
})
async function updateLearningProgress(docId) {
    if (!userInfoRes.userId) return
    let sendData = {
        docId, libId,
        userId: userInfoRes.userId,
    }
    await addLearningProgress(sendData)
}

</script>
<style scoped lang="scss">
.materials-file {
    // padding-bottom: 48px;
    height: calc(100vh - 164px - 21px);
    box-sizing: border-box;

    .main {
        height: calc(100% - 60px);
        overflow-y: auto;
    }

    .file-item {

        .file-title {
            padding-top: 16px;
            padding-bottom: 18px;
            border-bottom: 1px dotted #DDDDDD;

            .title {
                font-size: 24px;
                font-weight: bold;
                color: #2B5AA2;
                text-align: center;
                margin-bottom: 13px;
            }

            .date {
                font-size: 14px;
                color: #666666;
                text-align: center;
            }
        }

        .file-content {
            padding: 0 112px;
        }

    }

    :deep(.docx-wrapper) {
        background-color: transparent;
        padding: 0;
        padding-top: 18pt;

        section {
            box-shadow: none;
            width: 100% !important;
            padding: 0 !important;
        }
    }
}

.video-controls {
    width: 100%;
}
</style>